<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './role.data';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicTree, TreeItem } from '@/components/Tree';
  import { detailApi,saveApi } from '@/api/sys/user';

  import { useMessage } from '@/hooks/web/useMessage';
  import util from "@/utils/util";

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const treeData = ref<TreeItem[]>([]);
  const { createMessage } = useMessage();

  const wmUserId = ref('');
  const [registerForm, { resetFields, setFieldsValue, validate,updateSchema }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //打开弹层后的回调
    resetFields();
    setModalProps({ confirmLoading: false });
    // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
    // if (unref(treeData).length === 0) {
    //   treeData.value = (await getMenuList()) as any as TreeItem[];
    // }
    isUpdate.value = !!data?.isUpdate;
    wmUserId.value = '';
    let sc_json={
      label: '密码',
      field: 'passWord',
      required: false,
      ifShow:true,
      component: 'Input',
    }
    if (unref(isUpdate)) {
      console.log('---data.record:', data.record);
      let n_json=util.copy(sc_json);
      n_json.ifShow=false;
      updateSchema(n_json);

      wmUserId.value = data.record.wmUserId;
      let json = {
        wmUserId: wmUserId.value,
      };
      detailApi(json).then((res) => {
        console.log('---res::', res);
        if (res.code == 200) {
          let item = res.data;

          setFieldsValue(item);
        } else {
          createMessage.error(res.message);
        }
      });
    }else{
      //新增
      updateSchema(util.copy(sc_json));
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增登录账号' : '编辑登录账号'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      // TODO custom api
      values.wmUserId = wmUserId.value;
      // console.log(values);
      if (values.levels) {
        let ids = values.levels.join(',');
        values.levels = ids;
      }
      //保存
      saveApi(values)
        .then((res) => {
          // console.log("---res::",res)
          if (res.code == 200) {
            createMessage.success(res.message);
          } else {
            createMessage.error(res.message);
          }
        })
        .catch((res) => {
          createMessage.error(res.message);
        })
        .finally(() => {
          closeModal();
          emit('success');
        });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
